<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.userName" class="list-input" placeholder="搜索用户名称" @input="handleSearchInput"
               @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.userName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
    </view>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleSelectUser">
        <uni-icons type="plus" size="14" color="#007aff"/>
        <text>选择用户</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 用户列表 -->
    <view class="list-content">
      <view v-for="user in userList" :key="user.userId" class="list-item" @click="handleViewUser(user)">
        <view class="list-avatar">
          <uni-icons type="person" size="24" :color="user.status === '0' ? '#1890ff' : '#d9d9d9'"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ user.userName }}</text>
            <text class="list-subtitle">{{ user.nickName }}</text>
            <view class="status-badge" :class="user.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ user.status === '0' ? '正常' : '停用' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">ID：{{ user.userId }}</text>
            </view>
            <view class="detail-item" v-if="user.phonenumber">
              <uni-icons type="phone" size="14" color="#999"/>
              <text class="detail-text">{{ user.phonenumber }}</text>
            </view>
            <view class="detail-item" v-if="user.email">
              <uni-icons type="email" size="14" color="#999"/>
              <text class="detail-text">{{ user.email }}</text>
            </view>
            <view class="detail-item" v-if="user.dept">
              <uni-icons type="home" size="14" color="#999"/>
              <text class="detail-text">{{ user.dept.deptName }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"/>
              <text class="detail-text">{{ parseTime(user.createTime, '{y}-{m}-{d}') }}</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-danger" @click.stop="handleCancelAuth(user)">
            <uni-icons type="close" size="14" color="#ff3b30"/>
            <text class="action-text">取消授权</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="!loading && userList.length === 0" class="list-empty">
      <uni-icons type="person" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无分配的用户</text>
    </view>

    <!-- 加载更多 -->
    <view v-if="userList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText"></uni-load-more>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {allocatedUserList, authUserCancel} from '@/api/system/role'
import {parseTime} from '@/utils/ruoyi'

const {proxy} = getCurrentInstance()

// 页面参数
const roleId = ref(null)
const roleName = ref('')

// 数据定义
const userList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')
let searchTimer = null

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleId: null,
  userName: '',
  phonenumber: ''
})

// 页面初始化
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options

  roleId.value = Number(options.roleId)
  roleName.value = decodeURIComponent(options.roleName || '')
  queryParams.roleId = Number(options.roleId)

  // 获取用户列表
  getList()
})

// 获取用户列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await allocatedUserList(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        userList.value = newData
      } else {
        userList.value.push(...newData)
      }

      total.value = response.total || 0

      // 判断是否还有更多数据
      if (userList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    proxy.$modal.showToast('获取用户列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 搜索处理
function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleSearch()
  }, 300)
}

function handleSearch() {
  queryParams.pageNum = 1
  userList.value = []
  getList()
}

// 清空搜索
function handleClear() {
  queryParams.userName = ''
  handleSearch()
}

// 加载更多
function handleLoadMore() {
  if (loadStatus.value === 'more' && !loading.value) {
    queryParams.pageNum++
    getList()
  }
}

// 选择用户
function handleSelectUser() {
  uni.navigateTo({
    url: `/pages_system/role/selectUser?roleId=${roleId.value}&roleName=${encodeURIComponent(roleName.value)}`
  })
}

// 查看用户详情
function handleViewUser(user) {
  // 可以添加查看用户详情的逻辑
  console.log('查看用户:', user)
}

// 取消授权
async function handleCancelAuth(user) {
  const result = await proxy.$modal.confirm(`确认要取消"${user.userName}"的"${roleName.value}"角色吗？`)
  if (result) {
    try {
      const response = await authUserCancel({
        roleId: roleId.value,
        userId: user.userId
      })

      if (response.code === 200) {
        proxy.$modal.showToast('取消授权成功')
        // 刷新列表
        queryParams.pageNum = 1
        userList.value = []
        getList()
      } else {
        proxy.$modal.showToast(response.msg || '取消授权失败')
      }
    } catch (error) {
      console.error('取消授权失败:', error)
      proxy.$modal.showToast('取消授权失败')
    }
  }
}

// 刷新
function handleRefresh() {
  queryParams.pageNum = 1
  userList.value = []
  getList()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';
</style>